﻿using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Scenario;
[AppService]
public class MemberService : QyRepository<Member>
{
    private readonly string cacheKey;
    private readonly ApplicationContext _applicationContext;
    public MemberService(ApplicationContext applicationContext) : base(applicationContext)
    {
        cacheKey = GetEntityFullName();
        _applicationContext = applicationContext;
    }


    public async Task<PagedInfo<ViewMember>> GetPageListAsync(QueryMember parm)
    {
        var exp = Expressionable.Create<Member>();
        exp = exp.AndIF(parm.Status > 0, data => data.Status == parm.Status);
        exp = exp.AndIF(parm.DeptId != 0, data => data.DeptId == parm.DeptId);
        exp = exp.AndIF(parm.Name != null, data => data.Name.Contains(parm.Name));
        exp = exp.AndIF(parm.IdWork != null, data => data.IdWork.Contains(parm.IdWork));
        exp = exp.AndIF(parm.IdNumber != null, data => data.IdNumber.Contains(parm.IdNumber));
        if (parm.Uids == null)
            exp = exp.And(data => data.Uid == parm.Uid);
        else
            exp = exp.AndIF(!parm.Uids.Exists(x => x == -1), data => parm.Uids.Contains(data.Uid));

        return await Queryable()
            .LeftJoin<UserPost>((data, post) => data.PostId == post.Id)
            .LeftJoin<UserDept>((data, post, dept) => data.DeptId == dept.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.PostName), (data, post) => post.PostName.Contains(parm.PostName))
            .OrderBy((data) => data.Sort, OrderByType.Asc)
            .Select((data, post, dept) => new ViewMember()
            {
                DeptName = dept.Name,
                PostName = post.PostName,
                Id = data.Id.SelectAll()
            }, true)
            .ToPageAsync(parm);
    }

    public async Task<bool> GetByIdNumberAsync(string idNumber)
    {
        return await Queryable().FirstAsync(data => data.IdNumber == idNumber) == null;
    }

    public async Task<int> UpdateAsync(EditMember member)
    {

        Member getMember = await GetByIdAsync(member.Id);
        if (getMember == null)
            return -1;

        if (member.IdNumber != getMember.IdNumber && await GetByIdNumberAsync(member.IdNumber) == false)
            return -2;//判断用户是否重复

        getMember.DeptId = member.DeptId;
        getMember.PostId = member.PostId;
        getMember.Name = member.Name;
        getMember.Sex = member.Sex;
        getMember.IdNumber = member.IdNumber;
        getMember.IdWork = member.IdWork;
        getMember.DateOfBirth = member.DateOfBirth;
        getMember.Origin = member.Origin;
        getMember.Ethnic = member.Ethnic;
        getMember.Party = member.Party;
        getMember.WorkTime = member.WorkTime;
        getMember.GraduateInstitutions = member.GraduateInstitutions;
        getMember.Specialty = member.Specialty;
        getMember.Phone = member.Phone;
        getMember.Address = member.Address;
        getMember.Photo = member.Photo;
        getMember.Duties = member.Duties;
        getMember.Duty = member.Duty;
        getMember.Sort = member.Sort;
        getMember.Status = member.Status;
        return await UpdateAsync(getMember) > 0 ? 1 : 0;
    }

    /// <summary>
    /// 根据生日获取当天生日成员列表
    /// </summary>
    /// <param name="cacheTime"></param>
    /// <returns></returns>
    public async Task<List<ViewMember>> ListByDateOfBirth(int cacheTime = 600)
    {
        string cacheName = cacheKey + "_ListByDateOfBirth";
        List<ViewMember> list = await _applicationContext.ICacheManager.GetAsync<List<ViewMember>>(cacheName);
        if (list == null)
        {
            var exp = Expressionable.Create<Member>();
            exp = exp.And(data => data.DateOfBirth.ToString("MM-dd") == DateTime.Now.ToString("MM-dd"));
            list = await Queryable()
                        .LeftJoin<UserPost>((data, post) => data.PostId == post.Id)
                        .LeftJoin<UserDept>((data, post, dept) => data.DeptId == dept.Id)
                        .Where(exp.ToExpression())
                        .OrderBy((data) => data.Id, OrderByType.Asc)
                        .Select((data, post, dept) => new ViewMember()
                        {
                            DeptName = dept.Name,
                            PostName = post.PostName,
                            Name = data.Name
                        })
                        .ToListAsync();
            _applicationContext.ICacheManager.Set(cacheName, list, TimeSpan.FromSeconds(cacheTime));
        }
        return list;
    }

    /// <summary>
    /// 按部门获取成员列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<ViewMember>> ListByDeptId(int status = 0, int deptId = 0, int cacheTime = 600)
    {
        string cacheName = cacheKey + "_ListByDept";
        List<ViewMember> list = await _applicationContext.ICacheManager.GetAsync<List<ViewMember>>(cacheName);
        if (list == null)
        {
            var exp = Expressionable.Create<Member>();
            exp = exp.AndIF(deptId > 0, data => data.DeptId == deptId);
            exp = exp.And( data => data.Status != status);
            list = await Queryable()
                        .LeftJoin<UserPost>((data, post) => data.PostId == post.Id)
                        .LeftJoin<UserDept>((data, post, dept) => data.DeptId == dept.Id)
                        .Where(exp.ToExpression())
                        .OrderBy((data) => data.Sort, OrderByType.Asc)
                        .Select((data, post, dept) => new ViewMember()
                        {
                            DeptName = dept.Name,
                            PostName = post.PostName,
                            Name = data.Name.SelectAll()
                        })
                        .ToListAsync();
            _applicationContext.ICacheManager.Set(cacheName, list, TimeSpan.FromSeconds(cacheTime));
        }
        return list;
    }
}

